const uatTokenUrl = "http://uat-ha.fehorizon.com/femsp/uac/api/authing/grant/internaltoken?clientId=6530959bc23d3ce70acf228e&clientSecret=4bbba097085c1f8909fefdf8ddc034c8";
const prdTokenUrl = "http://ha.fehorizon.com/femsp/uac/api/authing/grant/internaltoken?clientId=656549b43a036f920faf8588&clientSecret=640a2ede0900c94776e0aea3ac3ff7d7";

const getJwtTokenSync = function (url) {
    try {
        const xhr = new XMLHttpRequest();
        xhr.open('POST', url, false); // 第三个参数设置为 false 表示同步请求
        xhr.send();

        if (xhr.status !== 200) {
            throw new Error(`HTTP error! status: ${xhr.status}`);
        }

        const data = JSON.parse(xhr.responseText);
        return "Bearer " + data.data.access_token;
    } catch (error) {
        console.error("Error fetching token:", error);
        throw error;
    }
};

const matchToken = function (str) {
    return str.includes('token')
        || str.includes('TOKEN')
        || str.includes('tk')
        || str.includes('TK');
};

const getToken = function (str) {
    let tokenUrl = uatTokenUrl;
    if (str.includes('prd')) {
        tokenUrl = prdTokenUrl;
    }
    return getJwtTokenSync(tokenUrl);
};

module.exports = {
    matchToken,
    getToken
}